import React from 'react'
import PropTypes from 'prop-types'
import { padleft, range } from '../utility'

class MonthPicker extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      isOpen: false,
      selectedYear: this.props.year,
      selectedMonth: this.props.month
    }
  }

  toggleDropdown = (event) => {
    event.preventDefault()
    this.setState({
      isOpen: !this.state.isOpen
    })
  }

  selectedYear = (event, yearNumber) => {
    event.preventDefault()
    this.setState({
      selectedYear: yearNumber
    })
  }

  selectedMonth = (event, monthNumber) => {
    event.preventDefault()
    this.setState({
      selectedMonth: monthNumber,
      isOpen: false
    })
    this.props.onChange(this.state.selectedYear, monthNumber)
  }

  render() {
    const { year, month } = this.props
    const { isOpen, selectedYear, selectedMonth } = this.state
    const monthRange = range(12,1)
    console.log(monthRange)
    const yearRange = range(9,-4).map(number => number+year)
    return(
      <div className="dropdown month-picker-component">
        <h4>选择月份</h4>
        <button className="btn btn-lg btn-secondary dropdown-toggle"
        id="dropdownMenuButton1"
        onClick={this.toggleDropdown}
        >
          {`${year}年-${padleft(month)}月`}
        </button>
        { isOpen &&
            <div className="dropdown-menu" style={{display: 'block'}} aria-labelledby="dropdownMenuButton1">
              <div className="row">
                <div className="col border-end">
                  {yearRange.map((yearNumber, index) => 
                    <a key={index}
                    className={yearNumber === selectedYear ? 'dropdown-item active': 'dropdown-item'}
                    href="/#"
                    onClick={event => {this.selectedYear(event, yearNumber)}}
                    >
                      {yearNumber}年
                    </a>
                  )}
                </div>
                <div className="col">
                {monthRange.map((monthNumber, index) => 
                    <a key={index}
                    className={monthNumber === selectedMonth ? 'dropdown-item active': 'dropdown-item'}
                    href="/#"
                    onClick = {event => {this.selectedMonth(event, monthNumber)}}
                    >
                      {padleft(monthNumber)}月
                    </a>
                  )}
                </div>
              </div>
            </div>
        }
      </div>
    )
  }
}

MonthPicker.propTypes = {
  year: PropTypes.number.isRequired,
  month: PropTypes.number.isRequired,
  onChange: PropTypes.number.isRequired
}

export default MonthPicker